import lexer.Reader;
import lexer.Tokenizer;
import parser.Parser;
import parser.symbol.Table;
import utils.Code;
import utils.CompileError;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
    public void getSourceCode(String[] args) {
        if (args.length != 0) {
            Code code = new Code(args[0]);
            System.out.println(code);
        }
    }

    public void lab(String[] args) {
        if (args.length < 2) {
            return;
        }
        Reader reader = new Reader(args[0]);
        reader.readFile();
        Tokenizer tokenizer = new Tokenizer(reader);
//        tokenizer.printAllToken();
        Parser parser = new Parser(tokenizer);
        try {
            parser.analyse();
            System.out.println("--end--");
            BufferedWriter out = new BufferedWriter(new FileWriter(args[1]));
            out.write(Table.llvm.toString());
            System.out.println(Table.llvm.toString());
            out.close();
        } catch (CompileError e) {
            System.out.println(Table.llvm.toString());
            Table.getInstance().printTable();
            System.out.println(parser.token);
            e.printStackTrace();
            System.exit(2);
        } catch (IOException e) {
            System.out.println("文件" + args[0]);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
//        t.localTest();
        t.getSourceCode(args);
        t.lab(args);

    }

    public void localTest() {
        String dir_name = "D:\\onedrive\\OneDrive - buaa.edu.cn\\编译\\lab\\homework\\file\\intput";
        String out_dir = "D:\\onedrive\\OneDrive - buaa.edu.cn\\编译\\lab\\homework\\file\\output\\";
        File[] files = new File(dir_name).listFiles();    //获取该文件夹下所有的文件(夹)名
        int len = files.length;
        for (int i = 0; i < len; i++) {
            if (files[i].isFile()) {
                String[] args = new String[2];
                args[0] = files[i].getAbsolutePath();
                args[1] = out_dir + files[i].getName();
                File out = new File(args[1]);
                try {
                    out.createNewFile();
                    System.out.println(args[0] + "  " + args[1]);
                    lab(args);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
